#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/15 22:28
# @Author : cjw
"""文件操作"""
from yaml import safe_load_all, safe_load, safe_dump

from server_task.base.base_file import BaseFile


class YmlOperator(BaseFile):
    """yml文件操作"""

    def __init__(self, yml_path: str, multi: bool = False):
        """
        :param yml_path: yml文件路径
        :param multi: 是否多节读取，yml文件通过'---'符号进行多节处理
        """
        super(YmlOperator, self).__init__(yml_path)
        self._multi = multi

    @property
    def data(self):
        """获取yml数据"""
        # 第一次获取数据时，才进行读取
        if not self._data:
            with open(self._file_path, encoding='utf-8') as f:
                if self._multi:
                    self._data = list(safe_load_all(f))
                else:
                    self._data = safe_load(f)
        return self._data

    def write(self, data):
        """
        python数据写入到yml文件中
        :param data: python格式数据
        :return:
        """
        with open(self._file_path, 'w', encoding='utf-8') as f:
            safe_dump(data, f)
